package com.pig4cloud.pig.module.controller.attendance;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.DateUtils;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.attendance.Attendance;
import com.pig4cloud.pig.module.api.entity.attendance.AttendanceGroup;
import com.pig4cloud.pig.module.api.entity.estate.Estate;
import com.pig4cloud.pig.module.api.entity.excel.AttendanceMonthExport;
import com.pig4cloud.pig.module.api.entity.property.Property;
import com.pig4cloud.pig.module.service.attendance.IAttendanceGroupService;
import com.pig4cloud.pig.module.service.attendance.IAttendanceService;
import com.pig4cloud.pig.module.service.estate.IEstateService;
import com.pig4cloud.pig.module.service.property.IPropertyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

/**
 * 考勤Controller
 *
 * @author ruoyi
 * @date 2022-09-30
 */
@Validated
@Api(value = "考勤控制器", tags = {"考勤管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/attendance")
public class AttendanceController {

    private final IAttendanceService attendanceService;
    private final IAttendanceGroupService attendanceGroupService;
    private final IEstateService estateService;
    private final IPropertyService propertyService;
    /**
     * 查询考勤列表
     */
    @ApiOperation("查询考勤列表")
    @PreAuthorize("@pms.hasPermission('module:attendanceList:list')")
    @GetMapping("/list")
    public TableDataInfo<Attendance> list(@Validated Attendance attendance) {
        QueryWrapper<Attendance> qw = new QueryWrapper<>();
        if(attendance.getSysUserId()!=null){
            qw.eq("sys_user_id",attendance.getSysUserId());
        }
        if(attendance.getDutyGroupId()!=null){
            qw.eq("duty_group_id",attendance.getDutyGroupId());
        }
        if(attendance.getState()!=null){
            qw.eq("state",attendance.getState());
        }
        if(StrUtil.isNotEmpty(attendance.getBeginDate())){
            qw.between("create_time", attendance.getBeginDate() + " 00:00:00",attendance.getEndDate() + " 23:59:59");
        }
        TableDataInfo<Attendance> td = PageUtils.buildDataInfo(attendanceService.page(PageUtils.buildPage(),qw));
        List<Attendance> list = td.getData();
        for(Attendance list1:list){
            AttendanceGroup attendanceGroup=attendanceGroupService.findById(list1.getDutyGroupId());
            list1.setDutyGroupName(attendanceGroup.getGroupName());
            if(list1.getEstateId()!=null){
                Estate estate = estateService.findById(list1.getEstateId());
                list1.setEstateName(estate.getEstateName());
            }
            if(list1.getPropertyId()!=null){
                Property property= propertyService.findById(list1.getPropertyId());
                list1.setPropertyName(property.getPropertyName());
            }
        }
        return td;
    }

    /**
     * 导出考勤列表
     */
    @ApiOperation("导出考勤列表")
    @PreAuthorize("@pms.hasPermission('module:attendanceList:export')")
    @SysLog("考勤")
    @GetMapping("/export")
    public List export(@Validated Attendance attendance) {
        QueryWrapper<Attendance> qw=new QueryWrapper<>();
        if (attendance.getDutyGroupId()!=null){
            qw.eq("duty_group_id",attendance.getDutyGroupId());
        }
        if(StrUtil.isNotEmpty(attendance.getBeginDate())){
            qw.between("create_time", attendance.getBeginDate() + " 00:00:00",attendance.getEndDate() + " 23:59:59");
        }
        List<Attendance> list = attendanceService.list(qw);
        for (Attendance list1:list){
            if (list1.getPropertyId()!=null){
                Property property=propertyService.findById(list1.getPropertyId());
                if (property!=null){
                    list1.setPropertyName(property.getPropertyName());
                }
            }
            if (list1.getEstateId()!=null){
                Estate estate=estateService.findById(list1.getEstateId());
                if (estate!=null){
                    list1.setEstateName(estate.getEstateName());
                }
            }
            if(list1.getCreateTime()!=null){
                list1.setCreateTimeStr(DateUtils.getTime(list1.getCreateTime()));
            }
            if (list1.getState()!=null){
                if (list1.getState()==1){
                    list1.setStateName("正常");
                }else if (list1.getState()==2){
                    list1.setStateName("迟到");
                }else if (list1.getState()==3){
                    list1.setStateName("旷工");
                }else if (list1.getState()==4){
                    list1.setStateName("请假");
                }
            }
            if (list1.getHolidayState()!=null){
                if (list1.getHolidayState()==0){
                    list1.setHolidayName("未请假");
                }else if (list1.getHolidayState()==1){
                    list1.setHolidayName("未处理");
                }else if (list1.getHolidayState()==2){
                    list1.setHolidayName("未批准");
                }else if (list1.getHolidayState()==3){
                    list1.setHolidayName("已批准");
                }
            }
            if (list1.getAmOrPm()!=null){
                if (list1.getAmOrPm()==0){
                    list1.setAmOrPmName("上午上班");
                }else if (list1.getAmOrPm()==1){
                    list1.setAmOrPmName("上午下班");
                }else if (list1.getAmOrPm()==2){
                    list1.setAmOrPmName("下午上班");
                }else if (list1.getAmOrPm()==3){
                    list1.setAmOrPmName("下午下班");
                }
            }
            if(list1.getIsOut()!=null){
                if (list1.getIsOut()==0){
                    list1.setIsOutName("正常");
                }else if (list1.getIsOut()==1){
                    list1.setIsOutName("外勤打卡");
                }else if (list1.getIsOut()==2){
                    list1.setIsOutName("请假");
                }
            }
        }
        // ExcelUtil<Attendance> util = new // ExcelUtil<Attendance>(Attendance.class);
        return  list;// util.exportExcel(list, "考勤");
    }

    /**
     * 获取考勤详细信息
     */
    @ApiOperation("获取考勤详细信息")
    @PreAuthorize("@pms.hasPermission('module:attendanceList:query')")
    @GetMapping("/{id}")
    public R<Attendance> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        Attendance attendance = attendanceService.getById(id);
        return R.ok(attendance);
    }

    /**
     * 新增考勤
     */
    @ApiOperation("新增考勤")
    @PreAuthorize("@pms.hasPermission('module:attendanceList:add')")
    @SysLog("考勤")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody Attendance attendance) {
        return R.okByRow(attendanceService.save(attendance) ? 1 : 0);
    }

    /**
     * 修改考勤
     */
    @ApiOperation("修改考勤")
    @PreAuthorize("@pms.hasPermission('module:attendanceList:edit')")
    @SysLog("考勤")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody Attendance attendance) {
        return R.okByRow(attendanceService.updateById(attendance) ? 1 : 0);
    }

    /**
     * 删除考勤
     */
    @ApiOperation("删除考勤")
    @PreAuthorize("@pms.hasPermission('module:attendanceList:remove')")
    @SysLog("考勤")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(attendanceService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }


    /**
     * 导出考勤列表
     */
    @ApiOperation("按月导出考勤列表")
    @PreAuthorize("@pms.hasPermission('module:attendanceList:export')")
    @SysLog("考勤")
    @GetMapping("/monthExport")
    public List monthExport(@Validated Attendance attendance) {
        Calendar c = Calendar.getInstance();
        int year=c.get(Calendar.YEAR);
        int month=c.get(Calendar.MONTH);
        if (month==0){
            month=12;
        }
        String time= year+"-"+month;
        QueryWrapper<Attendance> qw=new QueryWrapper<>();
        if (attendance.getSysUserId()!=null){
            qw.eq("sys_user_id",attendance.getSysUserId());
        }
        qw.like("create_time",time);
        List<Attendance> list = attendanceService.list(qw);
        List<AttendanceMonthExport> monthList=new ArrayList<>();
        int day=0;
        if (month==2||month==4||month==6||month==9||month==11){
            day=30;
        }else {
            day=31;
        }
        for (int i=1;i<=day;i++){
            if (i<10){
                String date=time+"-0"+i;
            }else {
                String date=time+"-"+i;
            }
            AttendanceMonthExport attendances = new AttendanceMonthExport();
            attendances.setSysUserId(attendance.getSysUserId());
            attendances.setMonth(month);
            attendances.setDay(i);
            for (Attendance list1:list){
                System.out.println("时间————————"+list1.getCreateTime());
            }
        }
        // ExcelUtil<AttendanceMonthExport> util = new // ExcelUtil<AttendanceMonthExport>(AttendanceMonthExport.class);
        return  list;// util.exportExcel(monthList, "考勤");
    }
}
